<?php

function register_my_menu() {
    register_nav_menu('header-menu', __('Header Menu'));
}

add_action('init', 'register_my_menu');

add_theme_support('post-thumbnails');

function tahrir_scripts() {
    wp_enqueue_script('tahrir_jquery', get_template_directory_uri() . '/js/jquery-1.8.3.min.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_easing', get_template_directory_uri() . '/js/jquery.easing.1.3.min.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_slidekit', get_template_directory_uri() . '/js/jquery.sliderkit.1.9.2.pack.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_mousewheel', get_template_directory_uri() . '/js/jquery.mousewheel.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_jscrollpane', get_template_directory_uri() . '/js/jquery.jscrollpane.min.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_tn3lite', get_template_directory_uri() . '/js/jquery.tn3lite.min.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_myJava', get_template_directory_uri() . '/js/myJava.js', array(), FALSE, TRUE);
    wp_enqueue_script('tahrir_main', get_template_directory_uri() . '/js/main.js', array(), FALSE, TRUE);
    $mainScriptData = array(
        'ajaxPath' => admin_url('admin-ajax.php'),
        'templateDir' => get_template_directory_uri()
    );
    wp_localize_script('tahrir_main', 'phpObj', $mainScriptData);
}

add_action('wp_enqueue_scripts', 'tahrir_scripts');

//Myfunctions
$mainNavCat = get_categories('child_of=' . get_cat_ID('main nav') . '&hide_empty=0');
$mainNavIds = array();
foreach ($mainNavCat as $child) {
    $mainNavIds[] = $child->cat_ID;
}

function getColorClassName($post) {
    global $mainNavIds;
    $postId = is_int($post) ? $post : $post->ID;
    $postCategories = wp_get_post_categories($postId);
    foreach ($postCategories as $cat) {
        if (in_array($cat, $mainNavIds)) {
            $category = get_category($cat);
            break;
        } else {
            continue;
        }
    }
    return $category;
}

function isChildOfCategory($category_id, $child_category_id = NULL) {
// Load all children of the category
    $children = get_categories('child_of=' . $category_id . '&hide_empty=0');

// Initialize an array for all child IDs
    $children_ids = array();

// Fill the array just with category IDs
    foreach ($children as $child) {
        $children_ids[] = $child->cat_ID;
    }

// Check whether the given child ID, or the current category, exists within the category
    return ($child_category_id !== NULL) ? in_array($child_category_id, $children_ids) : is_category($children_ids);
}

function getChosenLastUpdatedTime() {
    $chosenId = get_cat_ID('chosen');
    $args = array('category' => $chosenId, 'numberposts' => '1', 'orderby' => 'modified');
    $posts = get_posts($args);
    $posts = $posts[0];
    $time = $posts->post_modified;
    return time_ago($time);
}

function time_ago($date, $granularity = 2) {
    $date = strtotime($date);
    $difference = 0;
    while (empty($difference)) {
        $difference = time() - $date;
    }
    $periods = array('قرن' => 315360000,
        'سنة' => 31536000,
        'شهر' => 2628000,
        'أسبوع' => 604800,
        'يوم' => 86400,
        'س' => 3600,
        'د' => 60,
        'ث' => 1);

    $retval = '';
    foreach ($periods as $key => $value) {
        if ($difference >= $value) {
            $time = floor($difference / $value);
            $difference %= $value;
            $retval .= ($retval ? ' ' : '') . $time . ' ';
            $retval .= $key;
            $granularity--;
        }
        if ($granularity == '0') {
            break;
        }
    }
    return $retval;
}

function getVideoEmbedURL($videoURL) {
//    if (preg_match("^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$", $videoURL)) {
        $matches = '';
        preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $videoURL, $matches);
        $id = $matches[1];
        return "http://www.youtube.com/embed/$id";
//    } else {
//        return FALSE;
//    }
}

//ajax
function loadSection($isChosen = false, $section = -1, $extraCat = FALSE) {
    if ($section == -1) {
        $section = (int) $_REQUEST['section'];
    }
    $offest = (isset($_REQUEST['offset']) && $_REQUEST['offset'] != 1) ? $_REQUEST['offset'] : 0;
    $chosenCatId = get_cat_ID('chosen');
    if ($section === 0) {//all
        $theCategory = FALSE;
        $args = array('category' => $chosenCatId, 'numberposts' => '6', 'offset' => $offest);
    } else {
        if (term_exists($section, 'category')) {
            $theCategory = get_category($section);
            if (!$isChosen) {
                $catsArray = $extraCat ? array($chosenCatId, $section, $extraCat) : array($chosenCatId, $section);
                $args = array('category__and' => $catsArray, 'numberposts' => '6', 'offset' => $offest);
            } else {
                if ($extraCat) {
                    $catsArray = array($section, $extraCat);
                    $catsKey = 'category__and';
                } else {
                    $catsArray = $section;
                    $catsKey = 'category';
                }
                $args = array($catsKey => $catsArray, 'numberposts' => '6', 'offset' => $offest);
            }
        }
    }
    $posts = get_posts($args);
    $more = '';
    $output = '';
    getSectionOutput($posts, $output, $more);
    if (!$isChosen) {
        echo json_encode(array('output' => $output, 'more' => $more));
        exit;
    } else {
        return $output;
    }
}

add_action('wp_ajax_nopriv_loadSection', 'loadSection');
add_action('wp_ajax_loadSection', 'loadSection');

function loadProvince() {
    $provinceCatId = get_cat_ID('المحافظات');
    $newsCat = get_cat_ID('news');
    $section = (int) $_REQUEST['section'];
    $province = $_REQUEST['province'];
    $provinceSpecificId = get_cat_ID($province);
    $offest = (isset($_REQUEST['offset']) && $_REQUEST['offset'] != 1) ? $_REQUEST['offset'] : 0;
    if ($section === 0) {
        $catsArray = array($provinceCatId, $provinceSpecificId, $newsCat);
        $catKey = 'category__and';
    } else {
        $catsArray = array($section, $provinceCatId, $provinceSpecificId, $newsCat);
        $catKey = 'category__and';
    }
    $args = array($catKey => $catsArray, 'numberposts' => '6', 'offset' => $offest);
    $posts = get_posts($args);
    $more = '';
    $sectionOutput = '';
    getSectionOutput($posts, $sectionOutput, $more);
    //videos
    $videoCatId = get_cat_ID('videos');
    $videoPosts = get_posts(array('category__and' => array($videoCatId, $provinceSpecificId), 'numberposts' => 4));
    $videosOutput = getVideosOutput($videoPosts);
    //albums
    $albumCatId = get_cat_ID('album');
    $albums = get_posts(array('category__and' => array($albumCatId, $provinceSpecificId)));
    $albumtsOutput = getAlbumtsOutput($albums);
    echo json_encode(array(
        'section' => array(
            'output' => $sectionOutput,
            'more' => $more
        ),
        'videos' => array(
            'output' => $videosOutput
        ),
        'albums' => array(
            'output' => $albumtsOutput
        )
    ));
    exit;
}

add_action('wp_ajax_nopriv_loadProvince', 'loadProvince');
add_action('wp_ajax_loadProvince', 'loadProvince');

function getAlbumtsOutput($albumPosts) {
    $output = '';
    if ($albumPosts) {
        foreach ($albumPosts as $post) {
            $output .= "<li class='csport'>";
            $output .= "<a href='#' class='fetch-album' pid='" . $post->ID . "'>" . $post->post_title . "</a>";
            $output .= "<div class='up-triangle'></div>";
            $output .= "</li>";
        }
    }
    return $output;
}

function getVideosOutput($videoPosts) {
    $output = '';
    if (!empty($videoPosts)) {
        foreach ($videoPosts as $video) {
            $videoURL = $video->post_content;
            $output .= "<li>";
            $output .= "<iframe width = '465' height = '235'";
            $output .= " src = '" . getVideoEmbedURL($videoURL) . "' >";
            $output .= "</iframe>";
            $output .= "</li>";
        }
    }
    return $output;
}

function getSectionOutput($posts, &$output, &$more) {
    if (!empty($posts)) {
        $more = TRUE;
        foreach ($posts as $post) {
            setup_postdata($post);
            $theCategory = getColorClassName($post);
            $colorClass = 'c' . $theCategory->slug;
            $author = get_the_author();
            $tags = wp_get_post_tags($post->ID);
            $meta = get_post_meta($post->ID);
            $permalink = get_permalink($post->ID);
            if (has_post_thumbnail($post->ID)) {
                $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail');
            }
            $output .= "<div class='sectionOneNewBox $colorClass'>
                    <div class='sectionNewImage relative'>
                        <img src='$image[0]' alt='' />
                        <a href='$permalink' class='quickRead'> قراءة سريعه </a>
                        <a href='#' class='sectionOneName'>
                            <span>$theCategory->name</span>
                            <span class='right-triangle'></span>
                        </a>
                    </div>
                    <div class='sectionNewInfo'>
                        <a href='#'>
                            <span class='writerIcon'></span>
                            <span class='writerName'>$author</span>
                        </a>
                        <span class='postTimeIcon'></span>
                        <span class='postTimeIn'>" . date('n/j/Y', strtotime($post->post_date)) . "</span>

                        <div class='postShares'>
                            <span class='gPlusShares'></span>
                            <span>" . $meta['gplus'][0] . "</span>
                            <span class='twitterShares'></span>
                            <span>" . $meta['twitter'][0] . "</span>
                            <span class='facebookShares'></span>
                            <span>" . $meta['facebook'][0] . "</span>
                        </div><!-- postShare -->
                    </div><!-- sectionNewInfo -->
                    <div class='sectionNewContent'>
                        <h3><a href='#'>" . strip_shortcodes($post->post_content) . "</a></h3>
                        <div class='tags'>";
            $counter = count($tags);
            foreach ($tags as $tag) {
                $deli = ($counter === 1) ? '' : ',';
                $output.="<a href='#'>$tag->name</a>$deli ";
                $counter--;
            }
            $views = do_shortcode('[post_view id=' . $post->ID . ']');
            $output.="<span>" . $views . "</span>
                           </div><!-- tags -->
                        <span class='rating-static rating-40'></span>
                    </div>

                </div>";
        }
    } else {
        $more = FALSE;
        $output = 'لا يوجد المزيد';
    }
}

function loadAlbum($post = FALSE) {
    $postId = !$post ? $_REQUEST['post'] : $post;
    $gallery = get_post_gallery($postId, FALSE);
    $returnResults = array();
    if ($gallery) {
        $idArr = explode(',', $gallery['ids']);
        foreach ($idArr as $key => $id) {
            $curennt = array();
            $imagePost = get_post($id);
            $curennt['caption'] = $imagePost->post_excerpt;
            $curennt['src'] = $gallery['src'][$key];
            $returnResults[] = $curennt;
        }
    }
    if (!$post) {
        echo json_encode($returnResults);
        exit;
    } else {
        return $returnResults;
    }
}

add_filter('show_admin_bar', '__return_false');

add_action('wp_ajax_nopriv_loadAlbum', 'loadAlbum');
add_action('wp_ajax_loadAlbum', 'loadAlbum');

function loadProvinceNews() {
    $province = $_REQUEST['province'];
    $provinceCategory = get_cat_ID($province);
    $newsCateggory = get_cat_ID('news');
    $posts = get_posts(array('category__and' => array($provinceCategory, $newsCateggory), 'numberposts' => 4));
    $returnResults = array();
    foreach ($posts as $post) {
        $curent = array();
        $curent['title'] = $post->post_title;
        $curent['link'] = get_permalink($post->ID);
        $returnResults[] = $curent;
    }
    $title = 'اخبار محافظة ' . $province;
    echo json_encode(array('posts' => $returnResults, 'title' => $title));
    exit;
}

add_action('wp_ajax_nopriv_loadProvinceNews', 'loadProvinceNews');
add_action('wp_ajax_loadProvinceNews', 'loadProvinceNews');

function getThumbForAlbum($post) {
    $thumbId = get_post_thumbnail_id($post);
    if ($thumbId) {
        $returnResults = array();
        $thumbURL = wp_get_attachment_url($thumbId);
        $imagePost = get_post($thumbId);
        $returnResults['src'] = $thumbURL;
        $returnResults['caption'] = $imagePost->post_excerpt;
    } else {
        $returnResults = FALSE;
    }
    return $returnResults;
}

if (function_exists('register_sidebar'))
    register_sidebar();

function get_tweets($url) {
    $json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
    if (!$json_string) {
        return 0;
    }
    $json = json_decode($json_string, true);
    return intval($json['count']);
}

function get_likes($url) {
    $json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
    if (!$json_string) {
        return 0;
    }
    $json = json_decode($json_string, true);
    return intval($json[$url]['shares']);
}

function get_plusones($url) {
    $html = file_get_contents("https://plusone.google.com/_/+1/fastbutton?url=" . urlencode($url));
    if (!$html) {
        return 0;
    }
    libxml_use_internal_errors(TRUE);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $counter = $doc->getElementById('aggregateCount');
    libxml_use_internal_errors(FALSE);
    return intval($counter->nodeValue);
}

//Set Default Meta Value
function set_default_meta($post_ID) {
    $current_field_value = get_post_meta($post_ID, 'twitter', true);
    $default_meta = '1'; // value
    if ($current_field_value == '' && !wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'twitter', $default_meta, false);
        add_post_meta($post_ID, 'facebook', $default_meta, false);
        add_post_meta($post_ID, 'gplus', $default_meta, false);
        add_post_meta($post_ID, 'source', $default_meta, false);
    }
    return $post_ID;
}

add_action('wp_insert_post', 'set_default_meta');

function scedulesocialshareupdate() {
    if (!wp_next_scheduled('social_share_update')) {
        wp_schedule_event(mktime(5, 0, 0, date('m'), date('d'), date('Y')), 'twicedaily', 'social_share_update');
    }
}

function socialshareupdate() {
    $posts = get_posts(array('numberposts' => -1));
    if (!empty($posts)) {
        set_time_limit(0);
        foreach ($posts as $post) {
            $postLink = get_permalink($post->ID);
            $tw = get_tweets($postLink);
            $fb = get_likes($postLink);
            $gp = get_plusones($postLink);
            update_post_meta($post->ID, 'twitter', $tw);
            update_post_meta($post->ID, 'facebook', $fb);
            update_post_meta($post->ID, 'gplus', $gp);
        }
    }
}

add_action('wp', 'scedulesocialshareupdate');
add_action('social_share_update', 'socialshareupdate');

function makeClickableLinks($s) {
    return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $s);
}

function custom_tweet_template($tweet) {

    $output = "<div class='oneNewFS'>
                <div class='topONFS clearfix'>
                    <a href='https://twitter.com/tahrir_news' target='_blank'><img src='" . $tweet->user->profile_image_url . "' alt='' /></a>
                    <div class='twitterFollow'><a href='https://twitter.com/tahrir_news' class='twitter-follow-button' data-show-count='false' data-lang='en'>Follow @tahrir_news/</a></div>
                </div>
                <h3>" . makeClickableLinks($tweet->text) . "</h3>
                    <div class='twitterActions'>
                        <span></span><a href='https://twitter.com/intent/tweet?in_reply_to=" . $tweet->id_str . "'>Reply</a>*
                        <span class='retweet'></span><a href='https://twitter.com/intent/retweet?tweet_id=" . $tweet->id_str . "'>Retweet</a>*
                        <span></span><a href='https://twitter.com/intent/favorite?tweet_id=" . $tweet->id_str . "'>Favorite</a>*
                        <div><a href='#' title='" . $tweet->created_at . "'> منذ " . time_ago($tweet->created_at) . "</a></div>
                    </div>
            </div>";
    echo $output;
}

add_action('displaytweets_tweet_template', 'custom_tweet_template');

function getSportSubCat($categories, $sportNavId) {
    if (!empty($categories)) {

        foreach ($categories as $category) {
            if ($category->parent == $sportNavId) {
                return $category->term_id;
            } else {
                continue;
            }
        }
    }
    return FALSE;
}
